#include <unistd.h>
#include "chess_logic.h"
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <ctype.h>

// 棋子基础价值
const int PIECE_VALUES[256] = {
    [WHITE_PAWN] = 100, [BLACK_PAWN] = 100,
    [WHITE_KNIGHT] = 320, [BLACK_KNIGHT] = 320,
    [WHITE_BISHOP] = 330, [BLACK_BISHOP] = 330,
    [WHITE_ROOK] = 500, [BLACK_ROOK] = 500,
    [WHITE_QUEEN] = 900, [BLACK_QUEEN] = 900,
    [WHITE_KING] = 20000, [BLACK_KING] = 20000
};

// 初始化棋盘
void initialize_board(char board[8][8]) {
    // 设置初始棋子位置
    char initial_board[8][8] = {
        {'r', 'n', 'b', 'q', 'k', 'b', 'n', 'r'},
        {'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p'},
        {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
        {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
        {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
        {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '},
        {'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'},
        {'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'}
    };
    
    memcpy(board, initial_board, sizeof(initial_board));
}

// 检查特定位置是否被攻击
bool is_square_attacked(ChessGame *game, int target_row, int target_col, bool by_white) {
    // 遍历整个棋盘
    for (int row = 0; row < 8; row++) {
        for (int col = 0; col < 8; col++) {
            char piece = game->board[row][col];
            
            // 跳过空位置
            if (piece == EMPTY) continue;
            
            // 检查是否属于攻击方
            if (by_white && islower(piece)) continue;
            if (!by_white && isupper(piece)) continue;
            
            // 计算行列差
            int row_diff = target_row - row;
            int col_diff = target_col - col;
            
            // 根据棋子类型检查攻击
            switch (tolower(piece)) {
                case 'p': // 兵
                    if (by_white) {
                        // 白兵只能向上对角线攻击
                        if (row_diff == -1 && abs(col_diff) == 1) {
                            return true;
                        }
                    } else {
                        // 黑兵只能向下对角线攻击
                        if (row_diff == 1 && abs(col_diff) == 1) {
                            return true;
                        }
                    }
                    break;
                    
                case 'r': // 车
                    if ((row_diff == 0 || col_diff == 0) && !(row_diff == 0 && col_diff == 0)) {
                        // 检查路径是否畅通
                        int row_step = (row_diff != 0) ? (row_diff > 0 ? 1 : -1) : 0;
                        int col_step = (col_diff != 0) ? (col_diff > 0 ? 1 : -1) : 0;
                        int steps = abs(row_diff) + abs(col_diff);
                        
                        for (int i = 1; i < steps; i++) {
                            int r = row + row_step * i;
                            int c = col + col_step * i;
                            if (r == target_row && c == target_col) break;
                            if (game->board[r][c] != EMPTY) {
                                goto next_piece; // 路径不通，检查下一个棋子
                            }
                        }
                        return true;
                    }
                    break;
                    
                case 'n': // 马
                    if ((abs(row_diff) == 2 && abs(col_diff) == 1) ||
                        (abs(row_diff) == 1 && abs(col_diff) == 2)) {
                        return true;
                    }
                    break;
                    
                case 'b': // 象
                    if (abs(row_diff) == abs(col_diff) && row_diff != 0) {
                        // 检查路径是否畅通
                        int row_step = (row_diff > 0) ? 1 : -1;
                        int col_step = (col_diff > 0) ? 1 : -1;
                        for (int r = row + row_step, c = col + col_step; 
                             r != target_row; 
                             r += row_step, c += col_step) {
                            if (game->board[r][c] != EMPTY) {
                                goto next_piece; // 路径不通
                            }
                        }
                        return true;
                    }
                    break;
                    
                case 'q': // 后
                    if ((row_diff == 0 || col_diff == 0 || abs(row_diff) == abs(col_diff)) && 
                        !(row_diff == 0 && col_diff == 0)) {
                        // 检查路径是否畅通
                        int row_step = (row_diff != 0) ? (row_diff > 0 ? 1 : -1) : 0;
                        int col_step = (col_diff != 0) ? (col_diff > 0 ? 1 : -1) : 0;
                        int steps = (row_step != 0) ? abs(row_diff) : abs(col_diff);
                        
                        for (int i = 1; i < steps; i++) {
                            int r = row + row_step * i;
                            int c = col + col_step * i;
                            if (r == target_row && c == target_col) break;
                            if (game->board[r][c] != EMPTY) {
                                goto next_piece; // 路径不通
                            }
                        }
                        return true;
                    }
                    break;
                    
                case 'k': // 王
                    if (abs(row_diff) <= 1 && abs(col_diff) <= 1) {
                        return true;
                    }
                    break;
            }
            next_piece: ; // 继续检查下一个棋子
        }
    }
    return false;
}

// 更新将军状态
void update_check_status(ChessGame *game) {
    // 查找王的位置
    int white_king_row = -1, white_king_col = -1;
    int black_king_row = -1, black_king_col = -1;
    
    for (int row = 0; row < 8; row++) {
        for (int col = 0; col < 8; col++) {
            if (game->board[row][col] == WHITE_KING) {
                white_king_row = row;
                white_king_col = col;
            } else if (game->board[row][col] == BLACK_KING) {
                black_king_row = row;
                black_king_col = col;
            }
        }
    }
    
    // 更新将军状态
    game->white_in_check = is_square_attacked(game, white_king_row, white_king_col, false);
    game->black_in_check = is_square_attacked(game, black_king_row, black_king_col, true);
}

// 验证移动合法性
bool is_move_valid(ChessGame *game, int from_row, int from_col, int to_row, int to_col) {
    // 1. 检查是否在棋盘范围内
    if (from_row < 0 || from_row > 7 || from_col < 0 || from_col > 7 ||
        to_row < 0 || to_row > 7 || to_col < 0 || to_col > 7) {
        return false;
    }
    
    char piece = game->board[from_row][from_col];
    char target = game->board[to_row][to_col];
    
    // 2. 检查是否移动自己的棋子
    if (game->white_to_move && islower(piece)) return false;
    if (!game->white_to_move && isupper(piece)) return false;
    
    // 3. 检查目标位置是否已有己方棋子
    if (game->white_to_move && isupper(target)) return false;
    if (!game->white_to_move && islower(target)) return false;
    
    // 4. 根据棋子类型验证移动
    int row_diff = to_row - from_row;
    int col_diff = to_col - from_col;
    
    switch (tolower(piece)) {
        case 'p': // 兵
            {
                int direction = game->white_to_move ? -1 : 1;
                
                // 基本前进
                if (col_diff == 0 && target == EMPTY) {
                    // 前进1格
                    if (row_diff == direction) return true;
                    // 前进2格（初始位置）
                    if (row_diff == 2 * direction && 
                        ((game->white_to_move && from_row == 6) || 
                         (!game->white_to_move && from_row == 1))) {
                        // 检查路径是否畅通
                        if (game->board[from_row + direction][from_col] == EMPTY) {
                            return true;
                        }
                    }
                }
                // 吃子
                else if (abs(col_diff) == 1 && row_diff == direction) {
                    // 普通吃子
                    if (target != EMPTY) return true;
                    // 吃过路兵
                    if (to_col == game->en_passant_target && 
                        game->board[from_row][to_col] == (game->white_to_move ? 'p' : 'P')) {
                        return true;
                    }
                }
                return false;
            }
            
        case 'r': // 车
            if (row_diff != 0 && col_diff != 0) return false;
            // 检查路径是否畅通
            if (row_diff != 0) {
                int step = (row_diff > 0) ? 1 : -1;
                for (int r = from_row + step; r != to_row; r += step) {
                    if (game->board[r][from_col] != EMPTY) return false;
                }
            } else {
                int step = (col_diff > 0) ? 1 : -1;
                for (int c = from_col + step; c != to_col; c += step) {
                    if (game->board[from_row][c] != EMPTY) return false;
                }
            }
            return true;
            
        case 'n': // 马
            return (abs(row_diff) == 2 && abs(col_diff) == 1) ||
                   (abs(row_diff) == 1 && abs(col_diff) == 2);
            
        case 'b': // 象
            if (abs(row_diff) != abs(col_diff)) return false;
            // 检查路径是否畅通
            int row_step = (row_diff > 0) ? 1 : -1;
            int col_step = (col_diff > 0) ? 1 : -1;
            for (int r = from_row + row_step, c = from_col + col_step; 
                 r != to_row; 
                 r += row_step, c += col_step) {
                if (game->board[r][c] != EMPTY) return false;
            }
            return true;
            
        case 'q': // 后
            if (!(row_diff == 0 || col_diff == 0 || abs(row_diff) == abs(col_diff))) {
                return false;
            }
            // 检查路径是否畅通
            if (row_diff == 0) {
                int step = (col_diff > 0) ? 1 : -1;
                for (int c = from_col + step; c != to_col; c += step) {
                    if (game->board[from_row][c] != EMPTY) return false;
                }
            } else if (col_diff == 0) {
                int step = (row_diff > 0) ? 1 : -1;
                for (int r = from_row + step; r != to_row; r += step) {
                    if (game->board[r][from_col] != EMPTY) return false;
                }
            } else {
                int row_step = (row_diff > 0) ? 1 : -1;
                int col_step = (col_diff > 0) ? 1 : -1;
                for (int r = from_row + row_step, c = from_col + col_step; 
                     r != to_row; 
                     r += row_step, c += col_step) {
                    if (game->board[r][c] != EMPTY) return false;
                }
            }
            return true;
            
        case 'k': // 王
            // 普通移动
            if (abs(row_diff) <= 1 && abs(col_diff) <= 1) return true;
            
            // 王车易位
            if (abs(col_diff) == 2 && row_diff == 0) {
                // 检查是否满足易位条件
                if (game->white_to_move) {
                    if (from_row != 7 || from_col != 4) return false;
                    
                    // 短易位
                    if (col_diff > 0 && game->white_can_castle_kingside) {
                        // 检查路径是否畅通
                        if (game->board[7][5] == EMPTY && 
                            game->board[7][6] == EMPTY) {
                            // 检查是否通过被攻击的格子
                            if (!is_square_attacked(game, 7, 4, false) && 
                                !is_square_attacked(game, 7, 5, false) && 
                                !is_square_attacked(game, 7, 6, false)) {
                                return true;
                            }
                        }
                    }
                    // 长易位
                    else if (col_diff < 0 && game->white_can_castle_queenside) {
                        // 检查路径是否畅通
                        if (game->board[7][1] == EMPTY && 
                            game->board[7][2] == EMPTY && 
                            game->board[7][3] == EMPTY) {
                            // 检查是否通过被攻击的格子
                            if (!is_square_attacked(game, 7, 4, false) && 
                                !is_square_attacked(game, 7, 3, false) && 
                                !is_square_attacked(game, 7, 2, false)) {
                                return true;
                            }
                        }
                    }
                } else {
                    if (from_row != 0 || from_col != 4) return false;
                    
                    // 短易位
                    if (col_diff > 0 && game->black_can_castle_kingside) {
                        // 检查路径是否畅通
                        if (game->board[0][5] == EMPTY && 
                            game->board[0][6] == EMPTY) {
                            // 检查是否通过被攻击的格子
                            if (!is_square_attacked(game, 0, 4, true) && 
                                !is_square_attacked(game, 0, 5, true) && 
                                !is_square_attacked(game, 0, 6, true)) {
                                return true;
                            }
                        }
                    }
                    // 长易位
                    else if (col_diff < 0 && game->black_can_castle_queenside) {
                        // 检查路径是否畅通
                        if (game->board[0][1] == EMPTY && 
                            game->board[0][2] == EMPTY && 
                            game->board[0][3] == EMPTY) {
                            // 检查是否通过被攻击的格子
                            if (!is_square_attacked(game, 0, 4, true) && 
                                !is_square_attacked(game, 0, 3, true) && 
                                !is_square_attacked(game, 0, 2, true)) {
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
            
        default:
            return false;
    }
}

// 检查是否有任何合法移动
bool has_legal_moves(ChessGame *game) {
    // 尝试所有可能的移动
    for (int from_row = 0; from_row < 8; from_row++) {
        for (int from_col = 0; from_col < 8; from_col++) {
            char piece = game->board[from_row][from_col];
            
            // 跳过空位置和对手的棋子
            if (piece == EMPTY) continue;
            if (game->white_to_move && islower(piece)) continue;
            if (!game->white_to_move && isupper(piece)) continue;
            
            // 尝试所有可能的目标位置
            for (int to_row = 0; to_row < 8; to_row++) {
                for (int to_col = 0; to_col < 8; to_col++) {
                    // 跳过无效移动
                    if (!is_move_valid(game, from_row, from_col, to_row, to_col)) {
                        continue;
                    }
                    
                    // 模拟移动
                    char original_target = game->board[to_row][to_col];
                    game->board[to_row][to_col] = piece;
                    game->board[from_row][from_col] = EMPTY;
                    
                    // 保存原始将军状态
                    bool original_white_check = game->white_in_check;
                    bool original_black_check = game->black_in_check;
                    
                    // 更新将军状态
                    update_check_status(game);
                    
                    // 检查移动后是否解除将军
                    bool move_legal = true;
                    if ((game->white_to_move && game->white_in_check) ||
                        (!game->white_to_move && game->black_in_check)) {
                        move_legal = false;
                    }
                    
                    // 恢复棋盘状态
                    game->board[from_row][from_col] = piece;
                    game->board[to_row][to_col] = original_target;
                    game->white_in_check = original_white_check;
                    game->black_in_check = original_black_check;
                    
                    // 如果找到任何合法移动，返回true
                    if (move_legal) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}

// 检查游戏结束状态
void check_game_over(ChessGame *game) {
    // 更新将军状态
    update_check_status(game);
    
    // 检查是否有合法移动
    bool has_moves = has_legal_moves(game);
    
    // 将死：被将军且没有合法移动
    if ((game->white_in_check || game->black_in_check) && !has_moves) {
        game->game_over = true;
        game->winner = game->white_to_move ? 'B' : 'W'; // 当前玩家被将死，对手获胜
    }
    // 逼和：没有被将军但没有合法移动
    else if (!(game->white_in_check || game->black_in_check) && !has_moves) {
        game->game_over = true;
        game->winner = 'D'; // 平局
    }
}

// 执行移动
void make_move(ChessGame *game, int from_row, int from_col, int to_row, int to_col) {
    char piece = game->board[from_row][from_col];
    char target = game->board[to_row][to_col];
    
    // 记录移动
    game->last_move.from_row = from_row;
    game->last_move.from_col = from_col;
    game->last_move.to_row = to_row;
    game->last_move.to_col = to_col;
    
    // 处理吃过路兵
    if (tolower(piece) == 'p' && to_col == game->en_passant_target && 
        abs(to_col - from_col) == 1 && target == EMPTY) {
        int captured_row = game->white_to_move ? to_row + 1 : to_row - 1;
        game->board[captured_row][to_col] = EMPTY;
    }
    
    // 更新吃过路兵目标
    game->en_passant_target = -1;
    if (tolower(piece) == 'p' && abs(to_row - from_row) == 2) {
        game->en_passant_target = from_col;
    }
    
    // 处理王车易位
    if (tolower(piece) == 'k' && abs(to_col - from_col) == 2) {
        // 短易位
        if (to_col > from_col) {
            game->board[to_row][to_col - 1] = game->board[to_row][7];
            game->board[to_row][7] = EMPTY;
        } 
        // 长易位
        else {
            game->board[to_row][to_col + 1] = game->board[to_row][0];
            game->board[to_row][0] = EMPTY;
        }
        
        // 更新易位权利
        if (game->white_to_move) {
            game->white_can_castle_kingside = false;
            game->white_can_castle_queenside = false;
        } else {
            game->black_can_castle_kingside = false;
            game->black_can_castle_queenside = false;
        }
    }
    
    // 处理车移动（失去易位权利）
    if (tolower(piece) == 'r') {
        if (game->white_to_move && from_row == 7) {
            if (from_col == 0) game->white_can_castle_queenside = false;
            if (from_col == 7) game->white_can_castle_kingside = false;
        }
        if (!game->white_to_move && from_row == 0) {
            if (from_col == 0) game->black_can_castle_queenside = false;
            if (from_col == 7) game->black_can_castle_kingside = false;
        }
    }
    
    // 处理王移动（失去所有易位权利）
    if (tolower(piece) == 'k') {
        if (game->white_to_move) {
            game->white_can_castle_kingside = false;
            game->white_can_castle_queenside = false;
        } else {
            game->black_can_castle_kingside = false;
            game->black_can_castle_queenside = false;
        }
    }
    
    // 处理兵升变
    if (tolower(piece) == 'p' && (to_row == 0 || to_row == 7)) {
        // 设置升变标志
        game->pending_promotion = true;
        game->promote_row = to_row;
        game->promote_col = to_col;
        // 先移动兵到升变位置
        game->board[to_row][to_col] = piece;
        game->board[from_row][from_col] = EMPTY;
        
        // 更新将军状态
        update_check_status(game);
        
        // 检查游戏是否结束
        check_game_over(game);
        
        return; // 等待用户选择升变棋子
    }
    
    // 执行移动
    game->board[to_row][to_col] = piece;
    game->board[from_row][from_col] = EMPTY;
    
    // 更新游戏状态
    game->white_to_move = !game->white_to_move;
    if (!game->white_to_move) {
        game->fullmove_number++;
    }
    
    // 更新50步规则计数器
    if (tolower(piece) == 'p' || target != EMPTY) {
        game->halfmove_clock = 0;
    } else {
        game->halfmove_clock++;
    }
    
    // 更新将军状态
    update_check_status(game);
    
    // 检查游戏是否结束
    check_game_over(game);
}

// 评估棋盘状态（正数对白方有利，负数对黑方有利）
int evaluate_board(ChessGame *game) {
    int score = 0;
    
    // 计算棋子价值
    for (int row = 0; row < 8; row++) {
        for (int col = 0; col < 8; col++) {
            char piece = game->board[row][col];
            if (piece != EMPTY) {
                int piece_value = PIECE_VALUES[(int)piece];
                if (isupper(piece)) {
                    score += piece_value;
                } else {
                    score -= piece_value;
                }
            }
        }
    }
    
    // 考虑将军状态
    if (game->white_in_check) score -= 50;
    if (game->black_in_check) score += 50;
    
    // 考虑中心控制
    for (int row = 3; row <= 4; row++) {
        for (int col = 3; col <= 4; col++) {
            char piece = game->board[row][col];
            if (piece != EMPTY) {
                if (isupper(piece)) score += 10;
                else score -= 10;
            }
        }
    }
    
    // 考虑王的安全
    for (int row = 0; row < 8; row++) {
        for (int col = 0; col < 8; col++) {
            if (game->board[row][col] == WHITE_KING) {
                if (row > 1 && row < 6) score += 20; // 王在中心不太安全
            } else if (game->board[row][col] == BLACK_KING) {
                if (row > 1 && row < 6) score -= 20;
            }
        }
    }
    
    return score;
}

// AI进行移动
void ai_move(ChessGame *game) {
    game->ai_thinking = true;
    
    // 模拟思考时间（基于难度）
    int think_time = 500000 + (3 - game->ai_difficulty) * 500000; // 0.5-2秒
    usleep(think_time);
    
    // 收集所有可能的移动
    Move moves[200];
    int move_count = 0;
    
    // 尝试所有可能的移动
    for (int from_row = 0; from_row < 8; from_row++) {
        for (int from_col = 0; from_col < 8; from_col++) {
            char piece = game->board[from_row][from_col];
            
            // 跳过空位置和对手的棋子
            if (piece == EMPTY) continue;
            if (game->white_to_move && islower(piece)) continue;
            if (!game->white_to_move && isupper(piece)) continue;
            
            for (int to_row = 0; to_row < 8; to_row++) {
                for (int to_col = 0; to_col < 8; to_col++) {
                    if (is_move_valid(game, from_row, from_col, to_row, to_col)) {
                        // 模拟移动以检查是否合法（不会导致自己被将军）
                        char original_target = game->board[to_row][to_col];
                        game->board[to_row][to_col] = piece;
                        game->board[from_row][from_col] = EMPTY;
                        
                        // 保存原始将军状态
                        bool original_white_check = game->white_in_check;
                        bool original_black_check = game->black_in_check;
                        
                        // 更新将军状态
                        update_check_status(game);
                        
                        // 检查移动后是否解除将军
                        bool move_legal = true;
                        if ((game->white_to_move && game->white_in_check) ||
                            (!game->white_to_move && game->black_in_check)) {
                            move_legal = false;
                        }
                        
                        // 恢复棋盘状态
                        game->board[from_row][from_col] = piece;
                        game->board[to_row][to_col] = original_target;
                        game->white_in_check = original_white_check;
                        game->black_in_check = original_black_check;
                        
                        if (move_legal) {
                            // 记录移动
                            moves[move_count].from_row = from_row;
                            moves[move_count].from_col = from_col;
                            moves[move_count].to_row = to_row;
                            moves[move_count].to_col = to_col;
                            
                            // 评估移动
                            int score = 0;
                            
                            // 吃子得分
                            if (original_target != EMPTY) {
                                score += PIECE_VALUES[(int)original_target] * 2;
                            }
                            
                            // 将军得分
                            game->board[to_row][to_col] = piece;
                            game->board[from_row][from_col] = EMPTY;
                            update_check_status(game);
                            if ((game->white_to_move && game->black_in_check) ||
                                (!game->white_to_move && game->white_in_check)) {
                                score += 50;
                            }
                            game->board[from_row][from_col] = piece;
                            game->board[to_row][to_col] = original_target;
                            update_check_status(game);
                            
                            // 兵升变得分
                            if (tolower(piece) == 'p' && (to_row == 0 || to_row == 7)) {
                                score += 800; // 升变价值很高
                            }
                            
                            moves[move_count].score = score;
                            move_count++;
                        }
                    }
                }
            }
        }
    }
    
    if (move_count == 0) {
        // 没有合法移动，游戏应该已经结束
        game->ai_thinking = false;
        return;
    }
    
    // 选择最佳移动（或根据难度随机选择）
    int best_score = -100000;
    int best_index = 0;
    
    for (int i = 0; i < move_count; i++) {
        if (moves[i].score > best_score) {
            best_score = moves[i].score;
            best_index = i;
        }
    }
    
    // 根据难度引入随机性
    int selected_index = best_index;
    if (game->ai_difficulty < 3) {
        // 中等难度：80%选择最佳，20%随机
        if (rand() % 5 == 0 && move_count > 1) {
            do {
                selected_index = rand() % move_count;
            } while (selected_index == best_index);
        }
    }
    if (game->ai_difficulty == 1) {
        // 简单难度：50%选择最佳，50%随机
        if (rand() % 2 == 0 && move_count > 1) {
            do {
                selected_index = rand() % move_count;
            } while (selected_index == best_index);
        }
    }
    
    // 执行选中的移动
    Move selected = moves[selected_index];
    make_move(game, selected.from_row, selected.from_col, selected.to_row, selected.to_col);
    
    game->ai_thinking = false;
}
